<?php

/**
 * Représente un champ de formulaire
 *
 * @package cass
 * @author Mickaël CASTANHEIRO <mickael.castanheiro@gmail.com>
 * @version 1.0
 */

namespace cass\formulaire;

abstract class Field extends \cass\Element {

    protected $name;
    protected $slug;
    protected $value;
    protected $error;
    protected $required;
    protected $helper;
    protected $formulaire;
    protected $options;

    /**
     * Constructeur de la classe
     * @param <type> $_name
     * @param <type> $_value
     * @param <type> $_required
     * @param <type> $_helper
     */
    public function __construct($_name, $_value=null, $_required=true, $_helper=null) {
        $this->name = $_name;
        $this->slug = slugify($_name);
        $this->value = $_value;
        $this->required = $_required;
        $this->helper = $_helper;
        $this->options = array();
        $this->init();
    }

    /**
     * Exécuté à la création
     */
    public function init() {}

    /**
     * Renvoie le type de champ
     */
    public function getType() {
        $name = static::getClassName();
        return strtolower(substr($name, strrpos($name, '\\') + 1));
    }

    /**
     * Retourne le nom des variables qui doivent être rendues
     * @return <type>
     */
    public function getRenderVars() {
        return array();
    }

    /**
     * Affiche le champ
     */
    public function render() { 
        $template = new \cass\Template;
        $template->setName('_field');
        $template->setVars(array(
            'formSlug' => $this->getFormulaire()->getSlug(),
            'type' => $this->getType(),
            'name' => $this->getName(),
            'slug' => $this->getSlug(),
            'value' => $this->getValue(),
            'error' => $this->getError(),
            'helper' => $this->getHelper(),
            'options' => $this->getOptions(),
        ));

        foreach ($this->getRenderVars() AS $value) {
            $template->addToVars($value, $this->{$value});
        }

        $template->render();
    }

    /**
     * Récupère les données en post (ou en get..)
     */
    public function bind() {
        $POST = ( $this->getFormulaire()->getMethod() == 'post' ) ? $_POST : $_GET;
        if (isset($POST[$this->getSlug()])) {
            $this->setValue(trim($POST[$this->getSlug()]));
        }

        $this->check();
    }

    /**
     * Vérifie la validité du champ
     */
    public function check() {
        if ($this->isRequired() AND empty($this->value)) {
            $this->setError('Le champ est requis');
        }
    }

}

?>
